package com.mybatis.demo.utils;

import com.mybatis.demo.mapper.UserMapper;
import com.mybatis.demo.pojo.User;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MybatisUtils {
    public static SqlSessionFactory sqlSessionFactory() throws Exception {
        PooledDataSource pooledDataSource = new PooledDataSource();
        pooledDataSource.setDriver("com.mysql.jdbc.Driver");
        pooledDataSource.setUrl("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&&characterEncoding=UTF-8");
        pooledDataSource.setUsername("root");
        pooledDataSource.setPassword("123");
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(pooledDataSource);
        sqlSessionFactoryBean.setMapperLocations(resolveMapperLocations());
        return sqlSessionFactoryBean.getObject();
    }

    public static Resource[] resolveMapperLocations() {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<String> mapperLocations = new ArrayList<>();
        mapperLocations.add("classpath*:mapper/UserMapper.xml");
        List<Resource> resources = new ArrayList();
        if (mapperLocations != null) {
            for (String mapperLocation : mapperLocations) {
                try {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                } catch (IOException e) {
                    // ignore
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }

    public static SqlSessionFactory sqlSessionFactory2() throws IOException {
        InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    public static SqlSessionFactory sqlSessionFactory3() throws IOException {
        PooledDataSource pooledDataSource = new PooledDataSource();
        pooledDataSource.setDriver("com.mysql.jdbc.Driver");
        pooledDataSource.setUrl("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&&characterEncoding=UTF-8");
        pooledDataSource.setUsername("root");
        pooledDataSource.setPassword("123");
        JdbcTransactionFactory jdbcTransactionFactory = new JdbcTransactionFactory();
        Environment development = new Environment("development", jdbcTransactionFactory, pooledDataSource);
        Configuration configuration = new Configuration(development);
        ErrorContext.instance().resource("mapper/UserMapper.xml");
        InputStream inputStream = Resources.getResourceAsStream("mapper/UserMapper.xml");
        XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, "mapper/UserMapper.xml", configuration.getSqlFragments());
        mapperParser.parse();
        return new SqlSessionFactoryBuilder().build(configuration);
    }



    public static void main(String[] args) throws Exception {
//        SqlSessionFactory sqlSessionFactory = sqlSessionFactory();
//        SqlSessionFactory sqlSessionFactory = sqlSessionFactory2();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactory3();
        SqlSession session = null;
        try {
            session = sqlSessionFactory.openSession();
            UserMapper mapper = session.getMapper(UserMapper.class);
            User user = mapper.selectByPrimaryKey("000002");
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        } finally {
           if (session!=null){
               session.close();
           }
        }
    }
}
